package com.woniuxy.rabbit.kill.rabbit;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.woniuxy.rabbit.kill.util.ResponseResult;
import com.woniuxy.rabbit.kill.util.WebSocketUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.io.IOException;

/**
 * description: KillConsumer <br>
 * date: 2022/1/15 4:37 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

@Component
public class KillConsumer {

    //计数器：统计有多少个消息到达消费者
    private static int count = 1;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @RabbitListener(queues = "kill_queue")
    public void received(String userName, Channel channel, Message message) throws IOException, InterruptedException {
        //System.out.println(userName+":received");
        System.out.println(count++);
        //1、判断库存
        int num = (Integer) redisTemplate.opsForValue().get("num");
        if (num <= 0) {
            //库存不足 拒绝消息成为死信 channel.basicNack
            /**
             * 参数1：消息tag
             * 参数2：是否批量拒绝
             * 参数3：是否重新放入队列
             */
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            return;
        }
        //2、库存不足 删减库存、下订单
        num--;
        redisTemplate.opsForValue().set("num", num);

        //秒杀成功，确认收到消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        //System.out.println("kill success!");
        Thread.sleep(1000);
        //秒杀成功 通知用户
        Session session = WebSocketUtil.MESSAGEMAP.get(userName);
        //准备返回的数据
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setMessage("恭喜你抢购成功");
        responseResult.setData("订单号码");
        String data = new ObjectMapper().writeValueAsString(responseResult);

        WebSocketUtil.sendMessage(session,data);
    }
}
